from fastapi.responses import JSONResponse
from config import CONFIG

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from tortoise.contrib.fastapi import HTTPNotFoundError, register_tortoise
from api import router
import uvicorn
from client.etcd_client import something_schedule

app = FastAPI(**CONFIG.HTTP_CONFIG)
app.include_router(router)

register_tortoise(app,
                  db_url="mysql://{user}:{password}@{host}:{port}/{db_name}?charset=utf8mb4"
                  .format(user=CONFIG.MYSQL_USER, password=CONFIG.MYSQL_PASSWORD,
                          host=CONFIG.MYSQL_HOST, port=CONFIG.MYSQL_PORT, db_name=CONFIG.MYSQL_DB_NAME),
                  modules={"models": ["models"]},
                  generate_schemas=False,
                  add_exception_handlers=CONFIG.ADD_EXCEPTION_HANDLERS,
                  )


# app.register_listener(base.init_redis, 'before_server_start')
# app.register_listener(base.close_redis, 'after_server_stop')
@app.exception_handler(Exception)
async def exception(request: Request, exc: Exception):
    return JSONResponse(status_code=200,
                        content={"code": 500, "message": "{}".format(exc.args)})


app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


if __name__ == '__main__':
    # something_schedule()
    uvicorn.run('app:app',
                host=CONFIG.HOST,
                port=CONFIG.HTTP_PORT,
                reload=CONFIG.RELOAD,
                debug=CONFIG.DEBUG)


"""
6Ni58rALY13bl0Wh
"""